<?php
/**
 * Created by PhpStorm.
 * User: yanwenqing
 * Date: 2019/4/28
 * Time: 17:43
 */

class Http{
    CONST HOST = '0.0.0.0';
    CONST PORT = 8811;

    public $http = null;
    public function __construct()
    {
        $this->http = new swoole_http_server(self::HOST, self::PORT);

        $this->http->set([
            'enable_static_handler' => true,
            'document_root' => "/mnt/hgfs/D/www/swoole_tp_s/public/static",
            'work_num' => 5,
            'task_worker_num' => 4
        ]);

        $this->http->on('workerstart', [$this, 'onWorkerStart']);
        $this->http->on('request', [$this, 'onRequest']);
        $this->http->on('task', [$this, 'onTask']);
        $this->http->on('finish', [$this, 'onFinish']);
        $this->http->on('close', [$this, 'onClose']);

        $this->http->start();
    }

    /**
     * @param swoole_server $server
     * @param $worker_id
     */
    public function onWorkerStart(swoole_server $server, $worker_id){
        // 加载基础文件
        require __DIR__ . '/../thinkphp/base.php';
    }

    /**
     * @param $request
     * @param $response
     */
    public function onRequest($request, $response){
        // 设置全局变量
        // $_SERVER = [];
        if(isset($request->server)){
            foreach ($request->server as $k => $v){
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if(isset($request->header)){
            foreach ($request->header as $k => $v){
                $_SERVER[strtoupper($k)] = $v;
            }
        }

        $_GET = [];
        if(isset($request->get)){
            foreach ($request->get as $k => $v){
                $_GET[strtolower($k)] = $v;
            }
        }
        $_POST = [];
        if(isset($request->post)){
            foreach ($request->post as $k => $v){
                $_POST[strtolower($k)] = $v;
            }
        }
        // print_r($request->server);
        $_POST['http_server'] = $this->http;
        // var_dump($_POST['http_server']);
        //$this->http->task(['test' => '123']);

        ob_start();
        // 执行应用并响应
        try{
            \think\Container::get('app')->run()->send();
        }catch (Exception $exception){
            var_dump($exception->getMessage());
        }
        //echo PHP_EOL."action = ".(request()->action()).PHP_EOL;

        $res = ob_get_contents();
        ob_end_clean();

        // 输出缓冲区内容
        $response->end($res);
    }

    public function onTask($server, $taskId, $workerId, $data){
        // 根据传递的method分发不同的任务
        switch ($data['method']){
            case 'send':
                //cache('code'.$data['code'], $data['phone']);
                echo 'send----';
                break;
            default:

        }
        echo "task_id = ".$taskId.PHP_EOL;

        return "task work finish";
    }

    public function onFinish($server, $taskId, $data){

    }

    public function onClose($ws, $fd){

    }
}

$http = new Http();